<!-- src/views/admin/StoresList.vue -->
<template>
  <el-card>
    <div class="toolbar">
      <el-input
        v-model="filters.name"
        placeholder="名称或编码"
        clearable
        @clear="fetchList"
        @keyup.enter="fetchList"
        style="width: 200px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon> </template
      ></el-input>
      <el-select
        v-model="filters.status"
        placeholder="状态"
        clearable
        @change="fetchList"
        style="width: 120px"
      >
        <el-option label="开启" :value="1" />
        <el-option label="关闭" :value="0" />
      </el-select>
      <el-button type="primary" size="small" @click="openDialog()">
        <el-icon><Plus /></el-icon> 新增
      </el-button>
      <el-button
        type="danger"
        size="small"
        :disabled="!multiple.length"
        @click="onBatchDelete"
      >
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="list"
      stripe
      @selection-change="multiple = $event"
      style="width: 100%"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column align="center" prop="id" label="ID" width="80" />
      <el-table-column
        align="center"
        prop="name"
        label="门店名称"
        min-width="150"
      />
      <el-table-column
        align="center"
        prop="code"
        label="编码"
        min-width="120"
      />
      <el-table-column
        align="center"
        prop="manager"
        label="负责人"
        width="120"
      />
      <el-table-column align="center" prop="phone" label="电话" width="140" />
      <el-table-column align="center" label="状态" width="240">
        <template #default="{ row }">
          <div class="status-cell">
            <span v-if="row.status === 0" class="status-label inactive"
              >禁用</span
            >
            <el-switch
              :model-value="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => onToggle(row, val)"
              size="small"
            />

            <span v-if="row.status === 1" class="status-label active"
              >启用</span
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="createdAt"
        label="创建时间"
        width="180"
      />
      <el-table-column
        align="center"
        prop="updatedAt"
        label="更新时间"
        width="180"
      />
      <el-table-column align="center" label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-button
            circle
            type="primary"
            :icon="Edit"
            @click="openDialog(row)"
          >
          </el-button>
          <el-button circle type="danger" :icon="Delete" @click="onDelete(row)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, jumper, sizes, total"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        @current-change="
          pageNum = $event;
          fetchList();
        "
        @size-change="
          pageSize = $event;
          pageNum = 1;
          fetchList();
        "
      />
    </div>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" ref="formRef" label-width="100px" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="form.manager" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="saving">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </el-card>
</template>
  
  <script setup>
import { ref, reactive, onMounted } from "vue";
import {
  pageStores,
  getStore,
  createStore,
  updateStore,
  deleteStores,
  toggleStore,
} from "@/api/stores";
import { Search, Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

const filters = reactive({ name: "", status: null });
const list = ref([]);
const loading = ref(false);
const multiple = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 弹窗
const dialogVisible = ref(false);
const isCreate = ref(true);
const dialogTitle = ref("新增门店");
const form = reactive({
  id: null,
  name: "",
  code: "",
  manager: "",
  phone: "",
  status: 1,
});
const formRef = ref(null);
const saving = ref(false);

// 校验
const rules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入编码", trigger: "blur" }],
};

function fetchList() {
  loading.value = true;
  pageStores({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...filters,
  })
    .then((res) => {
      list.value = res.data.items;
      total.value = res.data.total;
    })
    .finally(() => (loading.value = false));
}

function openDialog(row) {
  if (row) {
    isCreate.value = false;
    dialogTitle.value = "编辑门店";
    Object.assign(form, row);
  } else {
    isCreate.value = true;
    dialogTitle.value = "新增门店";
    Object.assign(form, {
      id: null,
      name: "",
      code: "",
      manager: "",
      phone: "",
      status: 1,
    });
  }
  dialogVisible.value = true;
}

function onSubmit() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    saving.value = true;
    const api = isCreate.value ? createStore(form) : updateStore(form);
    api
      .then(() => {
        ElMessage.success(isCreate.value ? "新增成功" : "更新成功");
        dialogVisible.value = false;
        fetchList();
      })
      .finally(() => (saving.value = false));
  });
}

function onDelete(row) {
  ElMessageBox.confirm("确认删除？", "提示", { type: "warning" })
    .then(() => {
      return deleteStores([row.id].join(","));
    })
    .then(() => {
      ElMessage.success("删除成功");
      fetchList();
    });
}

function onBatchDelete() {
  ElMessageBox.confirm("确认批量删除？", "提示", { type: "warning" })
    .then(() => {
      return deleteStores(multiple.value.map((i) => i.id).join(","));
    })
    .then(() => {
      ElMessage.success("删除成功");
      multiple.value = [];
      fetchList();
    });
}

function onToggle(row, newStatus) {
  toggleStore(row.id, newStatus)
    .then(() => {
      ElMessage.success("状态更新成功");
      fetchList();
    })
    .catch(() => {
      // 回滚
      row.status = newStatus ? 0 : 1;
    });
}

onMounted(fetchList);
</script>
  
  <style scoped>
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
  align-items: center;
}
.pagination {
  text-align: right;
  margin-top: 12px;
}
</style>
  